﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using DTO;
using BUS;

namespace QuanLySach
{
    /// <summary>
    /// Interaction logic for LapHoaDonBanUserControl.xaml
    /// </summary>
    public partial class LapHoaDonBanUserControl : UserControl
    {
        private Section_DTO Section { get; set; }
        private MainWindow _parent;
        
        // Danh so thu tu trong danh sach Sach mua
        private int _stt;

        // Tong so tien cua hoa don
        private float _sumMoney;

        // Bien tam luu tru sach trong qua trinh xu ly
        private Sach_DTO _sach;

        #region Phuong thu xu ly
        public LapHoaDonBanUserControl(Section_DTO sect, MainWindow par)
        {
            _parent = par;
            this.Section = sect;
            _stt = 0;
            _sumMoney = 0;
            InitializeComponent();
        }

        private void UserControl_Loaded_1(object sender, RoutedEventArgs e)
        {
            PhatSinhMaHoaDon();
            ngayNhap.SelectedDate = System.DateTime.Now;
        }

        private void Thoat_Click_1(object sender, RoutedEventArgs e)
        {
            _parent.ChangeUI(new WelcomeUserControl(Section));
        }

        private void XuatHoaDon_Click_1(object sender, RoutedEventArgs e)
        {
            if (listSachNhap.Items.Count == 0)
            {
                MessageBox.Show("Không thể xuất phiếu vì danh sách Sách rỗng!", "Thông Báo", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            ThemHoaDonBanSach();
        }

        private void XoaSach_Click_1(object sender, RoutedEventArgs e)
        {
            // Tao dau sach duoc chon
            ChiTietHoaDon_DTO cthd = (ChiTietHoaDon_DTO)listSachNhap.SelectedItem;
            
            if (cthd == null)
                return;
            // Xoa sach trong list
            listSachNhap.Items.Remove(cthd);
            
            // Tinh lai tong tien
            _sumMoney -= cthd.DonGiaBan * cthd.SoLuongBan;
            tongTien.Text = _sumMoney.ToString();

            // Cap nhat lai STT
            ItemCollection list = listSachNhap.Items;
            for (int i = 0; i < list.Count; i++)
            {
                ChiTietHoaDon_DTO temp = (ChiTietHoaDon_DTO)list[i];
                temp.Stt = i + 1;
            }

            listSachNhap.Items.Refresh();
            CapNhatXoaButton();
            CapNhatXuatHoaDon();
        }

        private void HoaDonMoi_Click_1(object sender, RoutedEventArgs e)
        {
            LapHoaDonMoi();
        }

        private void ThemSach_Click_1(object sender, RoutedEventArgs e)
        {
            Them1Sach();
            CapNhatXuatHoaDon();
        }

        private void listSachNhap_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ChiTietHoaDon_DTO cthd = (ChiTietHoaDon_DTO)listSachNhap.SelectedItem;
            if (cthd == null)
                return;

            maSach.Text = cthd.MaSach.ToString();
            tenSach.Text = cthd.TenSach;
            soLuong.Text = cthd.SoLuongBan.ToString();
            donGiaBan.Text = cthd.DonGiaBan.ToString();
            CapNhatXoaButton();
        }
        #endregion

        #region Ham Ho Tro
        private void PhatSinhMaHoaDon()
        {
            int maLonNhat = HoaDon_BUS.HOADON.LayMaHoDonLonNhat();
            
            if (maLonNhat != -999)
                maHoadon.Text = (maLonNhat + 1).ToString();
            else
                maHoadon.Text = Convert.ToString(1);
        }

        private void DienThongTinKhachHang()
        {
            try
            {
                if (maKhachHang.Text == String.Empty)
                {
                    XoaThongTinKhachHang();
                    return;
                }
                int ms = Int32.Parse(maKhachHang.Text);
                KhachHang_DTO kh = KhachHang_BUS.KHACHHANG.LayKhachHang(ms);

                if (kh == null)
                {
                    // thong bao loi
                    MessageBox.Show("Ma khach hang khong hop le");
                    XoaThongTinKhachHang();
                    maKhachHang.Focus();
                    return;
                }

                hoTen.Text = kh.HoTen;
                diaChi.Text = kh.DiaChi;
                eMail.Text = kh.Email;
                dienThoai.Text = kh.DienThoai;
                tienNo.Text = kh.TienNo.ToString();
            }
            catch (FormatException ex)
            {
                MessageBox.Show("Ma khach hang phai la mot con so");
                XoaThongTinKhachHang();
                maKhachHang.Focus();
            }
            finally
            {
                CapNhatThemButton();
            }
        }

        private void DienThongTinSach()
        {
            try
            {
                if (maSach.Text == String.Empty)
                {
                    XoaThongTinSach();
                    return;
                }
                int ms = Int32.Parse(maSach.Text);
                _sach = Sach_BUS.SACH.LaySach(ms);

                if (_sach == null)
                {
                    // thong bao
                    MessageBox.Show("Ma sach khong hop le");
                    XoaThongTinSach();
                    maSach.Focus();
                    return;
                }

                tenSach.Text = _sach.TenSach;
                soLuongTon.Text = _sach.SoLuongTon.ToString();
                //maSach.Focus();
            }
            catch (FormatException)
            {
                MessageBox.Show("Ma sach phai la mot so");
                XoaThongTinSach();
                maSach.Focus();
                return;
            }
            finally
            {
                CapNhatThemButton();
            }
        }

        private void LapHoaDonMoi()
        {
            PhatSinhMaHoaDon();
            maKhachHang.Text = "";
            hoTen.Text = "";
            diaChi.Text = "";
            dienThoai.Text = "";
            eMail.Text = "";
            tienNo.Text = "";

            maSach.Text = "";
            tenSach.Text = "";
            soLuongTon.Text = "";
            soLuong.Text = "";
            donGiaBan.Text = "";

            listSachNhap.Items.Clear();
        }

        private void Them1Sach()
        {
            try
            {
                // Kiem tra MaKhachHang va MaNhanVien ko duoc rong
                if (maKhachHang.Text == "")
                {
                    MessageBox.Show("Mã Khách Hàng không được rỗng!", "Cảnh Báo", MessageBoxButton.OK, MessageBoxImage.Warning);
                    maKhachHang.Focus();
                    return;
                }

                if (maSach.Text == "")
                {
                    MessageBox.Show("Mã Sách không được rỗng!", "Cảnh Báo", MessageBoxButton.OK, MessageBoxImage.Warning);
                    maSach.Focus();
                    return;
                }

                // Lay tham so No khach hang
                float nokh = float.Parse(tienNo.Text);
                float tienno = ThamSo_BUS.THAMSO.LaySLNoToiDa();

                // Lay tham so kiem tra QD2
                int slton = Int32.Parse(soLuongTon.Text);
                int slban = Int32.Parse(soLuong.Text);
                int sltonsauban = ThamSo_BUS.THAMSO.LaySLTonToiThieuSauKhiBan();

                // Kiem tra QD2
                if (nokh >= tienno)
                {
                    MessageBox.Show("Tiền nợ khách hàng phải nhỏ hơn " + tienno.ToString() + " mới được mua sách!", "Cảnh Báo", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                if (slton - slban < sltonsauban)
                {
                    MessageBox.Show("Số lượng tồn của sách sau khi bán phải lớn hơn  " + sltonsauban.ToString() + " mới được mua sách!", "Cảnh Báo", MessageBoxButton.OK, MessageBoxImage.Warning);
                    soLuong.Focus();
                    soLuong.SelectAll();
                    return;
                }

                // Tang STT
                _stt += 1;
                
                // Lay don gia va so luong de tinh tong tien
                float dg = float.Parse(donGiaBan.Text);
                int sl =Int32.Parse(soLuong.Text);

                // Tao doi tuong CTHD
                ChiTietHoaDon_DTO cthd = new ChiTietHoaDon_DTO(_stt, Int32.Parse(maHoadon.Text), _sach.MaSach, _sach.TenSach, sl, dg);
                
                // Add CTHD vao list
                listSachNhap.Items.Add(cthd);
                
                // Tinh va hien tong tien
                _sumMoney += sl * dg;
                tongTien.Text = _sumMoney.ToString();
               
                maSach.Focus();
                maSach.SelectAll();
                _sach = null;
            }
            catch (Exception)
            {
                MessageBox.Show("Lỗi.! Không thể thêm Sách", "Lỗi", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
        }

        private void ThemHoaDonBanSach()
        {
            // Them Hoa Don vao CSDL
            HoaDon_BUS.HOADON.ThemHoaDon(new HoaDon_DTO(ngayNhap.ToString(), Int32.Parse(maKhachHang.Text), _sumMoney));

            int ms = HoaDon_BUS.HOADON.LayMaHoDonLonNhat();
            
            int c = listSachNhap.Items.Count;

            // Them CTHD vao CSDL
            for(int i = 0; i < c; i++)
            {
                ChiTietHoaDon_DTO cthd = (ChiTietHoaDon_DTO)listSachNhap.Items[i];
                ChiTietHoaDon_BUS.CHITIETHOADON.ThemChiTietHoaDon(cthd);
                Sach_DTO sach = Sach_BUS.SACH.LaySach(cthd.MaSach);
                sach.SoLuongTon -= cthd.SoLuongBan;
                Sach_BUS.SACH.SuaSach(sach); 

            }

            MessageBox.Show("Lập Hóa đơn thành công.!", "Thông Báo", MessageBoxButton.OK, MessageBoxImage.Information);
            LapHoaDonMoi();
        }
        #endregion

        private void maKhachHang_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            DienThongTinKhachHang();
        }

        private void CapNhatThemButton()
        {
            if (maSach.Text == String.Empty || soLuong.Text == String.Empty || donGiaBan.Text == String.Empty || hoTen.Text == String.Empty)
                ThemSach.IsEnabled = false;
            else
                ThemSach.IsEnabled = true;
        }

        private void XoaThongTinSach()
        {
            maSach.Text = String.Empty;
            tenSach.Text = String.Empty;
            soLuong.Text = string.Empty;
            soLuongTon.Text = String.Empty;
            donGiaBan.Text = string.Empty;
        }

        private void XoaThongTinKhachHang()
        {
            maKhachHang.Text = String.Empty;
            hoTen.Text = String.Empty;
            tienNo.Text = String.Empty;
            diaChi.Text = String.Empty;
            eMail.Text = String.Empty;
            dienThoai.Text = String.Empty;
        }

        private void soLuong_GotFocus(object sender, RoutedEventArgs e)
        {
            soLuong.SelectAll();
        }

        private void soLuong_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            try
            {
                if (soLuong.Text == String.Empty)
                    return;
                Int32.Parse(soLuong.Text);
            }
            catch (FormatException)
            {
                MessageBox.Show("So luong nhap phai la mot con so");
                soLuong.Focus();
            }
            finally
            {
                CapNhatThemButton();
            }
        }

        private void donGiaBan_GotFocus(object sender, RoutedEventArgs e)
        {
            donGiaBan.SelectAll();
        }

        private void donGiaBan_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            try
            {
                if (donGiaBan.Text == String.Empty)
                    return;
                Int32.Parse(donGiaBan.Text);
                ThemSach.IsEnabled = true;
                ThemSach.Focus();
            }
            catch (FormatException)
            {
                MessageBox.Show("Don gia ban phai la mot con so");
                donGiaBan.Focus();
            }
            finally
            {
                CapNhatThemButton();
            }
        }

        private void maSach_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            DienThongTinSach();
        }

        private void CapNhatXoaButton()
        {
            if (listSachNhap.SelectedIndex == -1)
                XoaSach.IsEnabled = false;
            else
                XoaSach.IsEnabled = true;
                
        }

        private void CapNhatXuatHoaDon()
        {
            if (listSachNhap.Items.Count == 0)
                XuatHoaDon.IsEnabled = false;
            else
                XuatHoaDon.IsEnabled = true;
        }

    }
}